package com.egoo.ticket.server.utils.activiti;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.RuntimeServiceImpl;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti5.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti5.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti5.engine.impl.pvm.process.ActivityImpl;
/**
 * @author：victor_tang
 * @Date ：2020/4/17
 * @Description：activit任务流转控制接口
 */
public class TaskFlowControlService {
	ProcessEngine _processEngine;
	private String _processId;

	public TaskFlowControlService(ProcessEngine processEngine, String processId)
	{
		this._processEngine = processEngine;
		this._processId = processId;
	}

	/**
	 *  跳转至指定活动节点
	 * @param targetTaskDefinitionKey
	 */
	public void jump(String targetTaskDefinitionKey){
		TaskEntity currentTask = (TaskEntity)_processEngine.getTaskService()
				.createTaskQuery()
				.processInstanceId(_processId).singleResult();
		jumps(currentTask,targetTaskDefinitionKey);
	}

	/**
	 * @param currentTaskEntity 当前任务节点
	 * @param targetTaskDefinitionKey  目标任务节点（在模型定义里面的节点名称）
	 */
	private void jumps(final TaskEntity currentTaskEntity, String targetTaskDefinitionKey){
		final ActivityImpl activity = getActivity(_processEngine,
				currentTaskEntity.getProcessDefinitionId(),targetTaskDefinitionKey);
		final ExecutionEntity execution = (ExecutionEntity)_processEngine.getRuntimeService()
				.createExecutionQuery().executionId(currentTaskEntity.getExecutionId()).singleResult();
		final TaskService taskService = _processEngine.getTaskService();
		((RuntimeServiceImpl)_processEngine.getRuntimeService()).getCommandExecutor()
				.execute(new Command<Void>() {
					@Override
					public Void execute(CommandContext commandContext) {

						//创建新任务
						execution.setActivity(activity);
						execution.executeActivity(activity);
						//删除当前的任务
						//不能删除当前正在执行的任务，所以要先清除掉关联
						currentTaskEntity.setExecutionId(null);
						taskService.saveTask(currentTaskEntity);
						taskService.deleteTask(currentTaskEntity.getId(),true);
						return null;
					}
				});
	}

	private ActivityImpl getActivity(ProcessEngine processEngine, String processDefId, String activityId)
	{
		ProcessDefinitionEntity pde = getProcessDefinition(processEngine,
				processDefId);
		return pde.findActivity(activityId);
	}

	private ProcessDefinitionEntity getProcessDefinition(ProcessEngine processEngine, String processDefId)
	{
		return (ProcessDefinitionEntity) ((RepositoryServiceImpl) processEngine.getRepositoryService())
				.getDeployedProcessDefinition(processDefId);
	}


}
